package com.youdo.careyes.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;

import com.youdo.careyes.utils.SpUtil;
import com.youdo.helper.UVCCameraHelper;

/**
 * SD卡监听
 *
 * @author ljb
 * @date 2025.11.28
 * @email 568838953@qq.com
 */
public class StorageBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "SDBroadcastReceiver";
    private final UVCCameraHelper mCameraHelper = UVCCameraHelper.getInstance();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null) {
            return;
        }
        String action = intent.getAction();
        Uri data = intent.getData();
        String path = data != null ? data.getPath() : null;
        Log.v(TAG, "onReceive: action:" + action + ",path:" + path);
        switch (action) {
            case Intent.ACTION_MEDIA_CHECKING:// SD卡正在检查(path = /dev/null)
                Log.v(TAG, "onReceive: SD卡正在检查");
                break;

            case Intent.ACTION_MEDIA_MOUNTED:// SD卡挂载成功(path:/storage/3130-3638)
                mCameraHelper.setSaveRootPath(SpUtil.getInstance().getSavePath());
                Log.v(TAG, "onReceive: SD卡挂载成功");
                break;

            case Intent.ACTION_MEDIA_EJECT:// SD卡请求卸载(path:/storage/3130-3638)
                mCameraHelper.setSaveRootPath(SpUtil.getInstance().getSavePath());
                Log.v(TAG, "onReceive: SD卡请求卸载");
                break;
            case Intent.ACTION_MEDIA_UNMOUNTED:// SD卡卸载成功(path:/storage/3130-3638)
                Log.v(TAG, "onReceive: SD卡已卸载");
                break;
            default:
                break;
        }
    }

    /**
     * 注册BroadcastReceiver
     */
    public void register(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
        intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        //intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        intentFilter.addDataScheme("file");
        context.registerReceiver(this, intentFilter);
    }

    /**
     * 注册BroadcastReceiver
     */
    public void unregister(Context context) {
        context.unregisterReceiver(this);
    }
}
